//
//  YWDownloadController2.m
//  videoTest3
//
//  Created by jun peng on 2022/7/28.
//

#import "YWDownloadController2.h"
#import "YWYoukuDetailController.h"

//#import "YWKLineCheatsVideoListParam.h"
//#import "YWKLineCheatsVideoListStatus.h"
//#import "YWKLineCheatsVideoListResultStatus.h"
//#import "YWKLineCheatsVideoListPageStatus.h"
//#import "YWKLineCheatsVideoListDataStatus.h"
//#import "YWKLineCheatsVideoListTool.h"

#import "YWDownloadCell.h"
#import "YWDownloadStatus.h"

#import "YWDownloadDataTaskStatus2.h"
#import "YWDownloadManager2.h"

#import "YWNoContentView2.h"
#import "YWSectionGroupStatus.h"

@interface YWDownloadController2 ()<UITableViewDelegate,UITableViewDataSource,YWDownloadCellDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barConstraintHeight;
@property (weak, nonatomic) IBOutlet YWTableView *tableView;

@property (nonatomic,strong)NSMutableArray *group;

//@property (nonatomic,strong)NSTimer *timer;

@property(nonatomic,weak)UIButton *rightItem;
@end

@implementation YWDownloadController2


//添加定时器
//-(void)addTimer{
//
//    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(loadLocalNewData) userInfo:nil repeats:YES];
//
//    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
//    self.timer = timer;
//}
//
////移除定时器
//-(void)removeTimer{
//
//    [self.timer invalidate];
//
//    self.timer = nil;
//
//}

//-(void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//
//    if (self.timer == nil) {
//        [self addTimer];
//    }
//}
//-(void)viewDidDisappear:(BOOL)animated{
//    [super viewDidDisappear:animated];
//    [self removeTimer];
//}

-(NSMutableArray*)group{
    if (_group == nil) {
        _group = [NSMutableArray array];
        
        YWSectionGroupStatus *sectionStatus0 = [[YWSectionGroupStatus alloc] init];
        sectionStatus0.headerTitle = @"     正在下载";
        sectionStatus0.remark = 0;
//        sectionStatus1.statusArray = @[[YWDownloadStatus new]];
        
        YWSectionGroupStatus *sectionStatus1 = [[YWSectionGroupStatus alloc] init];
        sectionStatus1.headerTitle = @"     下载完成";
        sectionStatus1.remark = 1;
//        sectionStatus2.statusArray = @[[YWDownloadStatus new]];
        
        [_group addObject:sectionStatus0];
        [_group addObject:sectionStatus1];
        
    }
    return _group;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.title = @"下载列表";
    self.barConstraintHeight.constant = self.navBar.frame.size.height;
    [self setupRightItem];
    
    //添加通知
    [self addObserveNotification];
    
    //获取下载任务列表
    [self loadLocalNewData];
    
    //创建下载任务
    [self createDownloadDataTask];
    
    
//         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ceshi:) name:@"ceshi" object:nil];
}



//-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
//
//}

//-(void)ceshi:(NSNotification *)notification{
//
//    //完成任务就要从字典移除模型
//
//    //拿出模型
//    NSNumber *sizeNum = notification.userInfo[@"size"];
//    CGFloat size = sizeNum.floatValue;
//    NSString *url = notification.userInfo[@"url"];
//    NSNumber *currentSizeNum = notification.userInfo[@"currentSizeNum"];
//
//
//
//    YWSectionGroupStatus *sectionStatus0 = self.group[0];
//
////    NSInteger i = 0;
//    for (YWDownloadStatus *status in sectionStatus0.statusArray) {
//
//        if ([status.VideoUrl isEqualToString:url]) {
//
//            status.currentSize = currentSizeNum.intValue;
//
////            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
//
//            break;
//        }
//
////        i++;
//
//    }
//
//}



//获取本地数据库数据
-(void)loadLocalNewData{

    NSArray *downloadinigStatusArray = [YWDownloadDataBaseTool getDownloadingAllNewsDataStatus];
    
    NSArray *finishDownloadStatusArray = [YWDownloadDataBaseTool getFinishAllNewsDataStatus];
    
    if (finishDownloadStatusArray.count == 0 && downloadinigStatusArray.count == 0) {
        
        //这里弄个noCotentView
        
        [self.view addSubview:self.noContentView];
        
        self.noContentView.frame = CGRectMake(0, self.navBar.height, Wi, self.view.height - self.navBar.height);
        
        self.noContentView.noContentType = YWNoContentView2Type_NoContentButNotConformBtn;
    }
    else{
        
        //移除noCotentView
        
          [self.noContentView removeFromSuperview];
        
        YWSectionGroupStatus *sectionStatus0 = self.group[0];
        YWSectionGroupStatus *sectionStatus1 = self.group[1];
        
        //按日期排序
        downloadinigStatusArray = [YWDownloadStatus compareDateWithArray:downloadinigStatusArray];
        finishDownloadStatusArray = [YWDownloadStatus compareDateWithArray:finishDownloadStatusArray];
        
        sectionStatus0.statusArray = [NSMutableArray arrayWithArray:downloadinigStatusArray];
        sectionStatus1.statusArray = [NSMutableArray arrayWithArray:finishDownloadStatusArray];
        
        
        [self.tableView reloadData];
    }
    

}

//创建下载任务
-(void)createDownloadDataTask{
    
//从正在任务数据库拿出属于扔给Manager处理，至于怎么处理Manager看着办
    NSArray *downloadinigStatusArray = [YWDownloadDataBaseTool getDownloadingAllNewsDataStatus];
    
    YWDownloadManager2 *manager = [YWDownloadManager2 sharedownloadManager];
    
    [manager beginDataTaskWithStatusArray:downloadinigStatusArray];
    
    
//拿VC传入来的单个模型判断是不是空，判断这模型两个数据库存不存在应该VC去判断(因为万一VC需要UI加入动画效果也是要判断的，只不过方法由Manager提供），扔给Manager处理
    if (self.downloadStatus != nil) {
        
        [YWDownloadManager2 judgeStatusExistInDataBase:self.downloadStatus.VideoUrl ifNoExist:^{
            
            
            YWDownloadStatus *dStatus = [[YWDownloadStatus alloc] init];
            
            dStatus.downloadType = YWDownloadType_Downloading;
            dStatus.Title = self.downloadStatus.Title;
            dStatus.PicUrl = self.downloadStatus.PicUrl;
            dStatus.Id = self.downloadStatus.Id;
            dStatus.VideoUrl = self.downloadStatus.VideoUrl;
            
            [manager createOneDataTaskWithStatus:dStatus];
        }];
        
    }
    
}


//NSString * const YWDownloadRefreshListNote = @"YWDownloadRefreshListNote";
//NSString * const YWStartDownloadNote = @"YWStartDownloadNote";
//NSString * const YWProgressDownloadNote = @"YWProgressDownloadNote";
//NSString * const YWFinishDownloadNote = @"YWFinishDownloadNote";
//NSString * const YWErrorDownloadNote = @"YWErrorDownloadNote";

//添加通知
-(void)addObserveNotification{
//    //手动开始/继续下载
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resumeDownloadNote:) name:YWResumeDownloadNote object:nil];
//    //手动暂停下载
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pauseDownloadNote:) name:YWPauseDownloadNote object:nil];
//    //手动移除下载
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeDownloadNote:) name:YWRemoveDownloadNote object:nil];
    
    //刷新列表回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(YWDownloadRefreshListNote:) name:YWDownloadRefreshListNote object:nil];
    
    //进度回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(YWProgressDownloadNote:) name:YWProgressDownloadNote object:nil];
    
    //开始下载回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startDownloadNote:) name:YWStartDownloadNote object:nil];
    //完成下载回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishDownloadNote:) name:YWFinishDownloadNote object:nil];
    //下载失败回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(errorDownloadNote:) name:YWErrorDownloadNote object:nil];
}
//刷新列表回调
-(void)YWDownloadRefreshListNote:(NSNotification *)notification{
    //再一次刷新列表
    [self loadLocalNewData];
}
//开始下载回调
-(void)startDownloadNote:(NSNotification *)notification{
     [self loadLocalNewData];
}
//完成下载回调
-(void)finishDownloadNote:(NSNotification *)notification{
    //再一次刷新列表
    [self loadLocalNewData];
}
//下载失败回调
-(void)errorDownloadNote:(NSNotification *)notification{
    //再一次刷新列表
    [self loadLocalNewData];
}

//进度回调
-(void)YWProgressDownloadNote:(NSNotification *)notification{
    
    //刷新单个cell应该相对不会太卡吧(实测还是挺顺滑的、只是finish的通知的时候因为要重新获取才卡一下、正在下载不会太卡)
    
    //拿出模型
    YWDownloadStatus *status = notification.userInfo[@"YWDownloadStatusKey"];

    YWSectionGroupStatus *sectionStatus0 = self.group[0];
    
    NSMutableArray *downloadinigStatusArray = sectionStatus0.statusArray;
    
    
    NSInteger i = 0;
    for (YWDownloadStatus *downloadStatus in downloadinigStatusArray) {
        
        if ([downloadStatus.VideoUrl isEqualToString:status.VideoUrl]) {
            
            downloadStatus.currentSize = status.currentSize;
            
//            YWLog(@"downloadStatus:%@ - status:%@",downloadStatus,status);
            
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            
            break;
        }
        
        i++;
    }
    
    
}

//---------------------------------------------------------------------------------------------------------------------------

//按cell的暂停继续按钮代理
-(void)downloadCell:(YWDownloadCell *)downloadCell didClickSituationBtnWithStatus:(YWDownloadStatus *)itemStatus{
    
    YWDownloadManager2 *manager = [YWDownloadManager2 sharedownloadManager];
    
    //具体做法应该交给Manager处理
    if (itemStatus.downloadType == YWDownloadType_Downloading) {
        [manager pauseOneDataTaskWithStatus:itemStatus];
    }
    else if (itemStatus.downloadType == YWDownloadType_Pause) {
        [manager continueOneDataTaskWithStatus:itemStatus];
    }
    else if (itemStatus.downloadType == YWDownloadType_Waiting) {
        [manager advanceOneDataTaskWithStatus:itemStatus];
    }
}

//按cell的删除按钮
-(void)cellDidClickDeleteWithIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) { //正在任务中的视频
        
        YWSectionGroupStatus *sectionStatus0 = self.group[0];
        
        YWDownloadStatus *downloadStatus = [sectionStatus0.statusArray objectAtIndex:indexPath.row];
        
        YWDownloadManager2 *manager = [YWDownloadManager2 sharedownloadManager];
        [manager removeOneDataTaskWithStatus:downloadStatus];
        
    }
    else{  //已经完成了的视频
        
        
        
    }
}

//---------------------------------------------------------------------------------------------------------------------------

-(void)setupRightItem{
    
    UIButton *rightItem = [[UIButton alloc] init];
    [rightItem setTitle:@"编辑" forState:UIControlStateNormal];
    [rightItem setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [rightItem setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateNormal];
//    [rightItem setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateHighlighted];
    rightItem.bounds = CGRectMake(0, 0, 100, 30);
    rightItem.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [rightItem setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
    [rightItem setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
    self.navBar.rightItem = rightItem;
    rightItem.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightItem addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];
    self.rightItem = rightItem;
}

-(void)edit{
    
    self.tableView.editing = !self.tableView.editing;
    
    if (self.tableView.editing) {
        
        [self.rightItem setTitle:@"完成" forState:UIControlStateNormal];
    }
    else{
        
        [self.rightItem setTitle:@"编辑" forState:UIControlStateNormal];
    }
}

-(void)askShow{
    
    YWAskView *askView = [YWAskView askView];
    
    askView.title = @"\n1、控制器VC：操作与显示模型数组：处理YWDownloadStatus的归档用来记录下载文件信息\n\n2、单例Manager：有一个字典用来装YWDownloadDataTaskStatus、用来规范下载任务、且是单例下载会App运行期间一直存在\n\n3、YWDownloadDataTaskStatus：每个独立下载个体、处理下载“自己”、把文件保存到沙盒与处理文件路径\n\n4、YWDownloadStatus：单个视频模型信息\n\n";
    [askView show];
    
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
//    [self removeTimer];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YWSectionGroupStatus *sectionStatus = self.group[indexPath.section];
    
    YWDownloadStatus *status = sectionStatus.statusArray[indexPath.row];
    
    YWDownloadCell *cell = [YWDownloadCell cellWithTableView:tableView];
    cell.delegate = self;
    cell.status = status;
    
    return cell;

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.group.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    YWSectionGroupStatus *group = self.group[section];
    return group.statusArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 105;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    YWSectionGroupStatus *scetionStatus = self.group[section];
    
    //没数据就不要头部了
    if (scetionStatus.statusArray.count == 0 ) {
        
        return 1;
    }
    else{
        
        return 30;
      
    }
    
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
 
    
    YWSectionGroupStatus *scetionStatus = self.group[section];
    
    //没数据就不要头部了
    if (scetionStatus.statusArray.count == 0 ) {
        
        return nil;
    }
    else{
        UILabel *label = [[UILabel alloc] init];
        label.text = scetionStatus.headerTitle;
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor blackColor];
        label.frame = CGRectMake(0, 0, Wi, 30);
        return label;
      
    }
    
}



//---------------------------------------------------------------------------------------------------------------------------

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    if (@available(iOS 11.0, *)) {
        [self customDeleteBtnAfteriOS11:tableView];
    }
}

- (void)customDeleteBtnAfteriOS11:(UITableView *)tableView {
    for (UIView *subview in tableView.subviews) {
        if ([NSStringFromClass([subview class]) isEqualToString:@"UISwipeActionPullView"]) {
            //设置按钮frame
            for (UIView * sonView in subview.subviews) {
                if ([sonView isKindOfClass:NSClassFromString(@"UISwipeActionStandardButton")]) {
                    sonView.frame = CGRectMake(-15, 0, 70, 70);
                    sonView.backgroundColor = YWColor(255, 110, 110);
                }
            }
        }
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath*)indexPath {
    MJWeakSelf
    if (@available(iOS 11.0, *)) {
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *_Nonnullaction, NSIndexPath *_NonnullindexPath) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除？" preferredStyle:UIAlertControllerStyleAlert];

        [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [weakSelf didClickDelete:self.listArrayM[indexPath.row] Ftype:KLEditPatientTypeDelete];
            
            [weakSelf cellDidClickDeleteWithIndexPath:indexPath];
        }]];

        [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];

        [self presentViewController:alertVc animated:YES completion:nil];

    }];

    rowAction.backgroundColor = [UIColor clearColor];
    return @[rowAction];
    }else {
        
        UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *_Nonnullaction, NSIndexPath *_NonnullindexPath) {
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除？" preferredStyle:UIAlertControllerStyleAlert];

            [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [weakSelf didClickDelete:self.listArrayM[indexPath.row] Ftype:KLEditPatientTypeDelete];
                
                [weakSelf cellDidClickDeleteWithIndexPath:indexPath];
            }]];

            [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];

            [self presentViewController:alertVc animated:YES completion:nil];

        }];

        rowAction.backgroundColor = [UIColor clearColor];
        return @[rowAction];
    }
}



/*
//tableView自带的左滑删除

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {

    //第二组可以左滑删除

    if (indexPath.section == 2) {

        return YES;

    }

    return NO;

}

// 定义编辑样式

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewCellEditingStyleDelete;

}

// 进入编辑模式，按下出现的编辑按钮后,进行删除操作

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {


        if (indexPath.section == 2) {

           //这里做删除操作

        }

    }

}

// 修改编辑按钮文字

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {

    return @"删除";

}
*/


@end
